package com.yueqian.sc.web.servlet;

import com.yueqian.sc.utils.CpachaUtil;

import javax.imageio.ImageIO;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;

/**
 * 生成验证码
 * url:http://localhost:8088/SelectCourse2/getCpacha
 */
@WebServlet("/getCpacha")
public class CpachaServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        CpachaUtil cpachaUtil = new CpachaUtil(4,100,30);//指定验证码长度、图片宽度、高度
        //生成随机的验证码(四个字符的字符串)
        String generatorVCode = cpachaUtil.generatorVCode();
        //将验证码保存到session
        HttpSession session = req.getSession();
        //设置超时
        //session.setMaxInactiveInterval(60);//以秒为单位
        //将验证码存放到session，主要是在登录的servlet中实现跟前台的验证码进行匹配
        session.setAttribute("vCode",generatorVCode);
        System.out.println("-----------------保存session:"+session.getId()+" "+generatorVCode);
        //生成一个验证码图片，响应到前台
        BufferedImage g = cpachaUtil.generatorRotateVCodeImage(generatorVCode,true);
        //回写
        ImageIO.write(g,"gif",resp.getOutputStream());
    }
}
